package com.lagou.rpc.netty;

import com.lagou.rpc.handler.RpcHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @ClassName RpcServerBootStrap
 * @Description nettyrpc服务端启动器
 * @Author playboy
 * @Date 2021/6/5 3:09 下午
 * @Version 1.0
 **/
@Component
@ConfigurationProperties(prefix = "spring.rpc")
public class RpcServerBootStrap {

	private int port;

	public void setPort(int port) {
		this.port = port;
	}

	@Autowired
	private RpcHandler rpcHandler;


	public void rpcStart() {
		NioEventLoopGroup boosLoopGroup = null;
		NioEventLoopGroup workLoopGroup = null;
		try {
			boosLoopGroup = new NioEventLoopGroup();
			workLoopGroup = new NioEventLoopGroup();
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(boosLoopGroup, workLoopGroup)
					.channel(NioServerSocketChannel.class)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel socketChannel) throws Exception {
							ChannelPipeline pipeline = socketChannel.pipeline();
							pipeline.addLast(new StringEncoder());
							pipeline.addLast(new StringDecoder());
							pipeline.addLast(rpcHandler);
						}
					});

			ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(port)).sync();
			System.out.println("rpc服务监听端口：" + port + "成功");
			future.channel().closeFuture().sync();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			if (boosLoopGroup != null) {
				boosLoopGroup.shutdownGracefully();
			}
			if (workLoopGroup != null) {
				workLoopGroup.shutdownGracefully();
			}
		}
	}

}
